package com.tjetc.controller;

import com.tjetc.common.JsonResult;
import com.tjetc.entity.UserAddress;
import com.tjetc.service.UserAddressService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/useraddress")
public class UserAddressController {
    @Autowired
    private UserAddressService userAddressService;

    /***
     * 添加用户的收货地址
     * @param userAddress
     * @return
     */
    @RequestMapping("add")
    public JsonResult add(UserAddress userAddress){
        //修改默认地址
        //逻辑写service中，要使用事务，每个操作都要判断
       // int i = userAddressService.change(userAddress.getUserId());
        int addId =  userAddressService.add(userAddress);
        if(addId<=0){
            return new JsonResult(1,"用户地址添加失败",addId);
        } else{
            return new JsonResult(0,"用户地址添加成功",addId);
        }
    }

    /***
     * 地址id查询地址信息
     * @param id
     * @return
     */
    @RequestMapping("query")
    public JsonResult queryById(Integer id){
        UserAddress userAddress = userAddressService.getUserAddressById(id);
        if(userAddress!=null) {
            return new JsonResult(0,"地址查询成功",userAddress);
        }
        else {
            return new JsonResult(1,"地址查询失败",userAddress);
        }
    }

    /***
     * 用户id查询用户所有地址信息
     * @param id
     * @return
     */
    @RequestMapping("all/{id}")
    public JsonResult all(@PathVariable Integer id){
        List<UserAddress> allUserAddress = userAddressService.getAllUserAddressByUserId(id);
        if (allUserAddress!=null){
            return new JsonResult(0,"用户所有地址查询成功",allUserAddress);
        }
        else {
            return new JsonResult(1,"用户地址查询失败",allUserAddress);
        }

    }

    /***
     * 地址id删除地址信息
     * @param id
     * @return
     */
    @RequestMapping("/delete/{id}")
    public JsonResult delete(@PathVariable("id") Integer id){
        int addId = userAddressService.deleteUserAddress(id);
        if(addId <= 0){
            return new JsonResult(1,"地址不存在",false);
        } else{
            return new JsonResult(0,"地址删除成功",true);
        }

    }

    /***
     * 更新地址信息
     * @param userAddress
     * @return
     */
    @RequestMapping("update")
    public JsonResult update(UserAddress userAddress){
        userAddress.setUpdateTime(LocalDateTime.now());
        int i = userAddressService.updateUserAddress(userAddress);
        if(i <= 0){
            return new JsonResult(1,"更新失败，请联系管理员",false);
        }
        else {
            return new JsonResult(0,"更新成功",true);
        }
    }

}
